/**
 * http://blog.csdn.net/sunxianghuang/article/details/52221913 
 * http://www.educity.cn/java/498061.html
 * concurrentskiplistmap
 */
package cn.com.colasoft.thread.concurrentcontainer;

import java.util.Arrays;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;

/**
 * 多种并发的Map性能测试
 */
public class ConcurrentMapTest {
	public static void main(String[] args) {
		Map<String, String> map = new ConcurrentHashMap<>();

		// 并发跳表Map.线程安全并且写入数据时保证数据有顺序
		//Map<String, String> map = new ConcurrentSkipListMap<>();

		/**
		 * HashTable线程安全,但是效率比较的低.因为在1.8之前 写的时候回锁住整个容器
		 * 而concurrenthashmap内部做了一些优化,是把内部分成了几段(segment),写数据
		 * 的时候不是锁住整个容器,而仅仅锁住某一个segment
		 */
		//Map<String, String> map = new Hashtable<>();
		//Map<String, String> map = Collections.synchronizedXXX(); // 等同于Hashtable效率比较低
		Random r = new Random();
		Thread[] ths = new Thread[100];
		CountDownLatch latch = new CountDownLatch(ths.length);
		long start = System.currentTimeMillis();
		for(int i=0; i<ths.length; i++) {
			ths[i] = new Thread(()->{
				for(int j=0; j<10000; j++) map.put("a" + r.nextInt(100000), "a" + r.nextInt(100000));
				latch.countDown();
			});
		}
		
		Arrays.asList(ths).forEach(t->t.start());
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		long end = System.currentTimeMillis();
		System.out.println(end - start);
	}
}
